<template>
  <div class="ys-map">

    <div class="map-wrapper">
      <div id="map"></div>
      <img class="position" src="" alt="position">
      <!-- <img class="nowposition" @click="locate" src="../../assets/icon/nowposition.svg" alt="nowposition"> -->
    </div>

    <div class="tips" stule="padding: 4px">
      <div>
        <span>附近查看：</span> 
        <Tag checkable @on-change="tagChange" :checked="check==currentAddress || check=='当前位置'" :name='currentAddress'  color="primary" style="border: 1px solid #ccc">当前位置</Tag>
        <Tag checkable @on-change="tagChange" :checked="check=='栋'" color="primary" name='栋' style="border: 1px solid #ccc">栋</Tag>
        <Tag checkable @on-change="tagChange" :checked="check=='店'" color="primary" name='店' style="border: 1px solid #ccc">店</Tag>
        <Tag checkable @on-change="tagChange" :checked="check=='小区'" color="primary" name='小区' style="border: 1px solid #ccc">小区</Tag>
        <Tag checkable @on-change="tagChange" :checked="check=='学校'" color="primary" name='学校' style="border: 1px solid #ccc">学校</Tag>
        <Tag checkable @on-change="tagChange" :checked="check=='餐饮'" color="primary" name='餐饮' style="border: 1px solid #ccc">餐饮</Tag>
      </div>
      <div style="border-bottom: 1px solid #ccc;margin-top:16px;padding-bottom:6px">
          <p>当前位置：{{currentAddress}} (以图上标记位置为准)</p>
      </div>
      <div style="text-align:left;padding: 6px 0px;border-bottom  : 1px solid #ccc" v-for="(item,index) in poiData" v-bind:key="index"   @click="selectAddress(item)">
          <p>{{item.title}}</p>
          <p>{{item.address}}</p>
      </div>
    </div>

    <div class="ys-search-address">
      <!-- <img class="back" src="../../assets/icon/back.svg" alt="back" @click="onBackClick"> -->
      <div class="ys-search-wrapper">
        <input type="text" v-model="searchValue" title="" id="suggestId" placeholder="定位不准？试试手动输入">
        <!-- <img src="../../assets/icon/close.svg" alt="search" @click="searchValue=''"> -->
      </div>
      <Button type="primary"  href="javascript:;" @click="onOkClick">保存定位</Button>
    </div>

    <div class="search-tips" id="result">
      
    </div>
  </div>
</template>

<script>
  export default {
    name: "Map",
    components: {

    },
    data(){
      return {
        map:null,
        searchValue:"",
        currentAddress:"",
        point:{},
        poiKeyword:"",
        potentialLocation:[],
        poiData: [],
        check: '当前位置'
      }
    },
    mounted(){
      this.$nextTick(()=>{
        this.initMaps();
        this.locate();
        this.getSuggestion();
      })
    },
    methods:{
        // 附近类型切换
        tagChange(checked,name) {
            if(checked) {
                this.check = name
                let potentialLocation = this.potentialLocation
                potentialLocation.map((item) => {
                    if(item.keyword == name) {
                        this.poiData = item.Qq
                        console.log('poiData',this.poiData)
                    }
                })
            }else {
                this.check = '暂未选择'
            }
        },
       initMaps(){
        this.map = new BMap.Map("map");
        let mPoint = new BMap.Point(116.404, 39.915);//Tiananmen Square
        this.map.centerAndZoom(mPoint,18);
        this.map.addEventListener("click", this.onMapClicked);
        this.map.addEventListener('dragend',()=>{
          let pixel = this.map.pointToOverlayPixel(this.map.getCenter());
          let point = this.map.overlayPixelToPoint({x:pixel.x,y:pixel.y});
          this.analyze(point);
        })
      },
      locate(){
        let map = this.map;
        let geolocation = new BMap.Geolocation();
        const vm = this;
        geolocation.getCurrentPosition(function(r){
          if(this.getStatus() === BMAP_STATUS_SUCCESS){
            map.panTo(r.point);
            vm.analyze(r.point);
          }else {
            console.log('当前定位失败 ',this.getStatus());
          }
        });
        //loading--
      },
      getAroundPOI(keyword){
        if(keyword) {
            let map = this.map;
            let mPoint = new BMap.Point(this.point.lng, this.point.lat);//h5 112.983323,28.141431
            let vm = this;
            let local =  new BMap.LocalSearch(map, {
            onSearchComplete(results){
                if (local.getStatus() === BMAP_STATUS_SUCCESS){
                //   let temp = [];
                //   console.log('返回结果',results)
                //   results.forEach(item=>{
                //     temp = temp.concat(item.Ar);
                //   });
                vm.potentialLocation = results;
                let check = vm.check
                    results.map((item) => {
                    if(item.keyword == check || item.keyword == vm.currentAddress) {
                        vm.poiData = item.Qq
                    }
                })
                }else{
                console.warn("get poi error ,code -> ",local.getStatus());
                }
            }
            });
            local.searchNearby(keyword,mPoint,1000);
        }
      },
      /**
       * Attention: 解析地址会有异常--有时候会解析正确，有时候只会解析到区
       * @param point lng and lat
       */
      analyze(point){//point:{lat:"",lng:""}
        let that = this
        const geoc = new BMap.Geocoder();
        geoc.getLocation(point, rs=>{

          console.log('测试',point,rs.point)
          that.point = rs.point;//===r.point
          that.currentAddress = rs.address;
          that.poiKeyword = rs.street||rs.address;
        });
      },
      /**
       * search tips
       */
      getSuggestion(){
        let ac = new BMap.Autocomplete({"input" : "suggestId","location" : this.map});
        ac.addEventListener("onconfirm", e=> {
          let _value = e.item.value;
          this.searchValue = _value.province + _value.city + _value.district + _value.street + _value.business;
          this.setPlace(this.searchValue);
        });
      },
      selectAddress(item){
        // 点击附近定位到附近
        if(item.point) {
            this.map.centerAndZoom(item.point, 18);
            this.point = item.point
        }
      },
      setPlace(val){
        
        let map = this.map;
        map.clearOverlays();
        const vm = this;
        let local = new BMap.LocalSearch(map, {
          onSearchComplete(){
            let pp = local.getResults().getPoi(0).point;
            vm.point = pp
            map.centerAndZoom(pp, 18);
            vm.analyze(pp);
          }
        });
        local.search(val);
      },
      onOkClick(){
        //todo: get this address and return.
        console.log("已选中当前位置!");
        console.log(this.currentAddress,this.point)
      }
    },

    watch:{
      poiKeyword(n){
        this.getAroundPOI(["栋","店","小区","学校","餐饮",n])
        
      }
    }
  }
</script>

<style lang="scss" scoped>
  .ys-map{
    height: 100%;
    overflow: hidden;
    position: relative;
    .map-wrapper{
      width: 70%;
      height: 100%;
      position: relative;

      #map{
        height: 100%;
      }
      img{
        width: 32px;
        object-fit: contain;
      }
      .position{
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-75%);//The bottom of the icon is centered,75  = 50(center) + 25(top)
        z-index: 100;
      }
      .nowposition{
        position: absolute;
        right: 20px;
        bottom:20px;
        z-index: 100;
      }

    }
    .tips{
      width: 30%;
      height: 100%;
      z-index: 999;
      overflow-y: scroll;
      position: absolute;
      padding: 1px 12px;
      right: 0;
      top: 0;
      background-color: #fff;
    }
    .ys-search-address{
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 50px;

      background: transparent;
      display: flex;
      align-items: center;
      input {
          background-color: #fff !important;
      }
      .back{
        width: 20px;
        object-fit: contain;
      }
      .okBtn{
        background: #FFDF5C;
        padding: 5px 12px;
        border: 1px solid #ffcf6e;
        color: #333;
        border-radius: 8px;
      }
      .ys-search-wrapper{
        width: 42%;
        padding-left:2%;
        border-radius: 20px;
        display: flex;
        align-items: center;
        input{
          padding: 8px 12px;
          background: transparent;

          width: 90%;
          height: 100%;
        }

        img{
          width: 12px;
          object-fit: contain;
        }
      }
    }
    .search-tips{
      position: absolute;
      left: 0;
      top: 50px;
      background: rgba(255,255,255,.8);
      border:1px solid #C0C0C0;
      height:auto;
      display:none;
    }
  }
</style>